package com.tanhua.dubbo.api;

import com.tanhua.dubbo.util.IdWorker;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi{

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存小视频数据
    @Override
    public String save(Video video) {
        //设置vid唯一标识
        Long vid = idWorker.getNextId("video");
        video.setVid(vid);

        mongoTemplate.save(video);
        return null;
    }

    //根据ids查询video
    @Override
    public List<Video> findByIds(List<Long> vids) {
        return mongoTemplate.find(Query.query(
                Criteria.where("vid").in(vids)
        ),Video.class);
    }

    //分页查询video
    @Override
    public List<Video> findByPage(Integer page, Integer pagesize) {

        return mongoTemplate.find(new Query().skip((page-1)*pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created"))),Video.class);
    }

    //查询用户所发视频并分页
    @Override
    public PageResult pageByUserId(Integer page, Integer pagesize, Long uid) {
        Query query = Query.query(Criteria.where("userId").is(uid));

        long count = mongoTemplate.count(query, Video.class);

        query.skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        List<Video> videoList = mongoTemplate.find(query, Video.class);
        return new PageResult(page,pagesize, (int) count,videoList);
    }
}
